package com.piece.admin.context.socket;

import com.alibaba.fastjson.JSONObject;
import com.piece.core.log.support.socket.SocketResponseMessage;
import com.piece.core.web.constants.WsConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
//@Component
//@ServerEndpoint(WsConstants.ENDPOINT_SOCKET + "/{token}")
public class WebSocket {

    // 连接会话
    private Session session;

    // 存放每个客户端对应的WebSocket对象。
    private static ConcurrentHashMap<String, WebSocket> webSocketMap = new ConcurrentHashMap<>();

    /**
     * 建立连接
     */
    @OnOpen
    public void onOpen(@PathParam(value = "token") String token, Session session) {
        this.session = session;
        webSocketMap.put(token, this);
        if (log.isDebugEnabled()) {
            log.info("【websocket消息】 有新的连接{}，总数{}", token, webSocketMap.size());
        }
    }

    /**
     * 连接关闭
     */
    @OnClose
    public void onClose(@PathParam(value = "token") String token) {
        webSocketMap.remove(token);
        if (log.isDebugEnabled()) {
            log.info("【websocket消息】 连接{}断开，总数{}", token, webSocketMap.size());
        }
    }

    /**
     * 接收客户端消息
     */
    @OnMessage
    public void onMessage(String text) {
        SocketResponseMessage message = JSONObject.parseObject(text, SocketResponseMessage.class);
        if (log.isDebugEnabled()) {
            log.info("【websocket消息】 收到客户端{}向{}发来的消息：{}", message.getSender(), message.getReceiver(), message.getContent());
        }
    }

    /**
     * 发送消息
     */
    public void sendMessage(String message) {
        sendMessage(null, message);
    }

    /**
     * 发送消息
     */
    public void sendMessage(String token, String message) {
        try {
            if (null == token) {
                Iterator entries = webSocketMap.entrySet().iterator();
                WebSocket webSocket;
                while (entries.hasNext()) {
                    Map.Entry entry = (Map.Entry) entries.next();
                    webSocket = (WebSocket) entry.getValue();
                    webSocket.session.getBasicRemote().sendText(message);
                }
            } else {
                WebSocket webSocket = webSocketMap.get(token);
                if (null != webSocket)
                    webSocket.session.getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }
}
